<template>
    <div class="list">
        <!-- 头部搜索 -->
        <Row>
            <Col :xs="24">
                <div class="margin-up-down">
                    <i-button type="info" @click="handleAddMedical" style="width:51px;height:35px;">
                        <i class = "iconfont icon-add" style="font-size:14px;margin-right:5px"></i>
                    </i-button>
                    <i-button type="info" @click="handleBatch" style="width:51px;height:35px;">
                        <i class = "iconfont icon-upload" style="font-size:14px;margin-right:5px"></i>
                    </i-button>
                </div>
                <div class="margin-up-down">
                    <Select class="select" v-model="filterObj.yplb"  clearable style="width: 160px" placeholder="请输入药品类型">
                        <Option :value="item.dictName" v-for="(item,index) in yplb" :key="index">{{item.dictName}}</Option>
                    </Select>
                </div>
                <div class="margin-up-down">
                    <Input v-model.trim="filterObj.ypmc" clearable style="width: 260px" placeholder="请输入药品名称" />
                </div>
                <div class="margin-up-down">
                    <Input class="input" clearable v-model.trim="filterObj.scqymc" style="width: 260px" placeholder="请输入药品厂家" />
                </div>
                <div class="margin-up-down">
                <i-button type="primary" icon="ios-search" @click="handleSearch" style="font-size:14px;width:51px;height:35px;"></i-button>
                    <i-button @click="handleReset" style="width:51px;height:35px;">
                        <i class = "iconfont icon-gengxin" style="font-size:14px;margin-right:5px"></i>
                    </i-button>
                </div>
            </Col>
        </Row>
        <!-- 列表 -->
        <div class="table">
            <Table 
                size="small" 
                :columns="columns" 
                :data="data1"
                @on-selection-change="selectChange"
                :loading="loading"
                no-data-text="未查询到符合条件的记录"
                stripe>
            </Table>               
            <div class="page">
                <Page :total="count" :current='filterObj.pageNo' :page-size="filterObj.pageSize" show-total show-elevator @on-change="loadPage"/>
            </div>
        </div>
        <!-- 编辑/查看/新建弹窗 -->
        <Modal
            v-model="showMedicalModal"
            width="800"
            @on-visible-change="(e) => {!e && $refs['formInline'].resetFields()}"
            class="drugmanagement-commondrug-list-MedicalModal">
            <p slot="header">
                <span>{{{add: '添加药品', edit: '编辑药品', review: '查看药品'}[modalType]}}</span>
            </p>
            <div>
                <Form
                    ref="formInline"
                    :model="formData"
                    :rules="ruleValidate"
                    label-position="left"
                    :label-width="60"
                   >
                    <Row v-if="showMedicalModal">
                        <Col span="24" class="left-part">
                            <h3 class="title">基本信息</h3>
                            <Row gutter='32' class="content">                        
                                <Col span="12">
                                    <FormItem prop="yplb" label="药品类别：" :label-width="75" class="hongdian contentitem">
                                        <Select
                                            v-model="formData.yplb"
                                            clearable
                                            filterable>
                                            <Option
                                                v-for="(item, index) in yplb"
                                                :key="index"
                                                :value="item.dictName">{{item.dictName}}</Option>
                                        </Select>
                                    </FormItem>
                                    <FormItem label="定义编码：" class="contentitem">
                                        <Input
                                            v-model="formData.code"
                                            clearable
                                            :maxlength="18"
                                            placeholder="请输入药品编码" />
                                    </FormItem>
                                    <FormItem prop="ypmc" label="药品通用名：" :label-width="85" class="hongdian">
                                        <Input
                                            v-model="formData.ypmc"
                                            clearable
                                            :maxlength="32"
                                            placeholder="请输入药品通用名" />
                                    </FormItem>
                                    <FormItem prop="ypgg" label="规格：" class="hongdian">
                                        <Input
                                            v-model="formData.ypgg"
                                            clearable
                                            :maxlength="50"
                                            placeholder="请输入药品规格" />
                                    </FormItem>
                                    <FormItem prop="scqymc" label="厂家名称：" :label-width="75" class="hongdian">
                                        <Input
                                            v-model="formData.scqymc"
                                            clearable
                                            :maxlength="64"
                                            placeholder="请输入厂家名称" />
                                    </FormItem>
                                    <FormItem prop="zxdw" label="基本单位：" :label-width="75" class="hongdian">
                                        <Select
                                            v-model="formData.zxdw"
                                            clearable
                                            filterable>
                                            <Option
                                                v-for="(item, index) in zxdw"
                                                :key="index"
                                                :value="item.dictName">{{item.dictName}}</Option>
                                        </Select>
                                    </FormItem>
                                    <FormItem label="数量关系：" class="contentitem">
                                        <Input
                                            v-model="formData.slgx"
                                            clearable
                                            :maxlength="4"
                                            placeholder="请输入数量关系" 
                                            style="width:50%" />
                                            <div>
                                                <small class="tishi">（备注：基本单位与包装单位的换算关系。）</small>
                                            </div>                              
                                    </FormItem>
                                </Col>
                                <Col span="12">
                                    <FormItem prop="drugCalss" label="药理分类：" class="contentitem">
                                        <Select
                                            v-model="formData.drugCalss"
                                            clearable
                                            filterable>
                                            <Option
                                                v-for="(item, index) in drugCalss"
                                                :key="index"
                                                :value="item.dictName">{{item.dictName}}</Option>
                                        </Select>
                                    </FormItem>
                                    <FormItem prop="pzwh" label="批准文号：" :label-width="75" class="hongdian">
                                        <Input
                                            v-model="formData.pzwh"
                                            clearable
                                            :maxlength="26"
                                            placeholder="请输入批准文号" />
                                    </FormItem>
                                    <FormItem label="商品名：" class="contentitem">
                                        <Input
                                            v-model="formData.ypmb"
                                            clearable
                                            :maxlength="32"
                                            placeholder="请输入药品商品名" />
                                    </FormItem>
                                    <FormItem prop="ypjx" label="剂型：" class="hongdian">
                                        <Select
                                            v-model="formData.ypjx"
                                            clearable
                                            filterable>
                                            <Option
                                                v-for="(item, index) in ypjx"
                                                :key="index"
                                                :value="item.dictName">{{item.dictName}}</Option>
                                        </Select>
                                    </FormItem>
                                    <FormItem prop="scqydm" label="厂家编码：" class="contentitem">
                                        <Input
                                            v-model="formData.scqydm"
                                            clearable
                                            :maxlength="16"
                                            placeholder="请输入厂家编码" />
                                    </FormItem>
                                    <FormItem prop="zxbzdw" label="包装单位：" :label-width="75" class="hongdian">
                                        <Select
                                            v-model="formData.zxbzdw"
                                            clearable
                                            filterable>
                                            <Option
                                                v-for="(item, index) in zxbzdw"
                                                :key="index"
                                                :value="item.dictName">{{item.dictName}}</Option>
                                        </Select>
                                    </FormItem>
                                    <FormItem prop="status" label="在用状态：" :label-width="75" class="hongdian">
                                        <RadioGroup
                                            v-model="formData.status">
                                            <Radio label="0" value="0">
                                                停用
                                            </Radio>
                                            <Radio label="1" value="1">
                                                在用
                                            </Radio>
                                        </RadioGroup>
                                    </FormItem>
                                </Col>
                                <Col span="24">
                                    <FormItem label="药品说明：" class="contentitem">
                                        <Input
                                            v-model="formData.content"
                                            placeholder="请输入药品说明"
                                            :maxlength="500"
                                            type="textarea" />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Col>
                    </Row>
                    <Row v-if="showMedicalModal">
                        <Col span="24" class="left-part">
                            <h3 class="title">常规用法信息</h3>
                            <Row gutter = "32" class="content"> 
                                <Col span="12">
                                    <FormItem label="默认给药路径：" :label-width="90" class="contentitem">
                                        <Select
                                            v-model="formData.ypyf"
                                            placeholder =  '请选择默认给药路径'
                                            clearable
                                            filterable>
                                            <Option
                                                v-for="(item, index) in ypyf"
                                                :key="index"
                                                :value="item.dictName">{{item.dictName}}</Option>
                                        </Select>
                                    </FormItem>
                                    <FormItem label="默认最小剂量：" :label-width="90" class="contentitem">
                                        <Input
                                            v-model="formData.attr1"
                                            clearable
                                            :maxlength="9"
                                            placeholder="请输入最小剂量" />
                                    </FormItem>
                                </Col>
                                <Col span="12">
                                    <FormItem label="默认用药频次：" :label-width="90" class="contentitem">
                                        <Select
                                            v-model="formData.yypc"
                                            placeholder =  '请选择用药频次'
                                            clearable
                                            filterable>
                                            <Option
                                                v-for="(item, index) in yypc"
                                                :key="index"
                                                :value="item.dictName">{{item.dictName}}</Option>
                                        </Select>
                                    </FormItem>
                                    <FormItem label="默认最小剂量单位：" :label-width="110" class="contentitem">
                                        <Select
                                            v-model="formData.attr2"
                                            placeholder =  '请选择剂量单位'
                                            clearable
                                            filterable
                                            >
                                            <Option
                                                v-for="(item, index) in attr2"
                                                :key="index"
                                                :value="item.dictName">{{item.dictName}}</Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                                <Col span="24">
                                    <FormItem label="数量关系：" class="contentitem">
                                        <Input
                                            v-model="formData.yzslgx"
                                            clearable
                                            :maxlength="4"
                                            placeholder="请输入数量关系" 
                                            style="width:20%"
                                            />
                                        <small class="tishi">（备注：基本单位与最小剂量单位的换算关系。如设置为0时，无计算关系）</small>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Col>
                    </Row>                   
                </Form>
                <div class="btn-group" v-if="modalType !== 'review'">
                    <Button style="width:75px;height:35px;" class="save" type="primary" icon="ios-checkmark" :loading="saveLoading"  @click="handleSave" :disabled='disabledSave'>保存</Button>
                    <Button style="width:75px;height:35px;" class="close" @click="() => {showMedicalModal = false; $refs['formInline'].resetFields();}">
                        <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i> 关闭
                    </Button>
                </div>
            </div>
        </Modal>
        <!-- 删除确认弹窗 -->
        <Modal
            v-model="showDelModal"
            title="确认删除弹窗"
            class="drugmanagement-commondrug-list-delModal">
            <p>删除后不可恢复，确认删除所选项吗？</p>
            <div slot="footer">
                <Button style="width:75px;height:35px;" class="cancel-btn btn" @click="showDelModal = false">
                    <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>  取消
                </Button>
                <Button style="width:75px;height:35px;" class="save-btn btn" icon="ios-checkmark" type="primary" :loading="delLoading" @click="handleDel">确认</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
const filterObj = {
    yplb: null,
    ypmc: null,
    // code: null,
    scqymc: null,
    // status: 'all',
    pageNo: 1,
    pageSize: '10',
};

const formData = {
    // id: null, //药品编码
    pzwh: '', //批准文号
    ypmc: '', //药品通用名
    ypmb: '', //商品名
    code: '', // 药品编码
    yplb: '', //药品类别
    drugCalss: '', // 药理分类
    zxdw: '', // 基本单位
    zxbzdw: '', // 包装单位
    ypjx: '', // 剂型
    attr1: '', // 最小剂量
    ypgg: '', // 规格
    attr2: '', // 剂量单位
    scqymc: '', // 厂家名称
    scqydm: '', // 厂家代码
    ypyf: '', // 默认给药路径
    status: '0',// 在用状态
    yypc: '', // 用药频次
    content: '', // 药品说明
    slgx: '',   //数量关系
    yzslgx: ''   //医嘱数量关系
}
import api from "@/api/commonApi";
import aesUtils from "@/plugins/aes-utils.js";
import store from "@/store";
export default {
    data() {
        return {
            params: {
                uId: ""
            },
            filterObj: this.deepClone(filterObj),
            // 限制条件
            ruleValidate:{
                // 药品类别：
                yplb:[
					{
						// 是否校验
						required: true,
						// 提示文字
						message: "请选择药品类别",
						// 触发事件
						trigger: "change"
					}
                ],
                pzwh: [ 
                    { required: true, message: '请输入批准文号', trigger: 'change' } 
                ],
                ypmc: [ 
                    { required: true, message: '请输入药品通用名', trigger: 'change' } 
                ],
                ypgg: [
                    { required: true, message: '请输入药品规格', trigger: 'change' }
                ],
                ypjx: [
                    { required: true, message: '请选择剂型', trigger: 'change' }
                ],
                scqymc: [
                    { required: true, message: '请输入厂家名称', trigger: 'change' }
                ],
                zxdw: [
                    { required: true, message: '请选择基本单位', trigger: 'change' }
                ],
                zxbzdw: [
                    { required: true, message: '请选择包装单位', trigger: 'change' }
                ],
                status: [
                    { required: true, message: '请选择在用状态', trigger: 'change' }
                ],
            },
            count: 0,
            columns: [
                {type: 'sum', title: '排序', width: 60, align: 'center',
                    render: (h, params) => {
                        let sum = (this.filterObj.pageNo-1)*this.filterObj.pageSize + params.index +1;
                        return h("span", sum);
                    }
                },
                { title: "药品类型", key: "yplb", align: "center" },
                { title: "剂型", key: "ypjx", align: "center"},
                { title: "药品名称", key: "ypmc", align: "center" },
                
                { title: "药品规格", key: "ypgg", align: "center"},
                { title: "生产厂家", key: "scqymc", align: "center"},
                { title: "批准文号", key: "pzwh", align: "center"},
                {
                    title: "状态",
                    key: "status",
                    align: "center",
                    render: (h, params) => {
                        return ['未启用', '在用', '停用'][params.row.status]
                    }
                },
                {
                    title: "设置",
                    key: "iOperate",
                    width: 200,
                    align: "center",
                    render: (h, params) => {
                        return h('div',[
                                h('sapn', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        color: '#5362e1',
                                        margin: "0px 6px"
                                    },
                                    on: {
                                        click: () => {
                                            this.handleEdit(params)
                                        }
                                    }
                                }, '编辑'),
                                '|',
                                h('span', {
                                    props: {
                                        size: 'small'
                                    },
                                    style: {
                                        color: '#21c780',
                                        margin: "0px 6px"
                                    },
                                    on: {
                                        click: () => {
                                            this.handleReview(params)
                                        }
                                    }
                                }, '详情'),
                                (params.row.status === '0') ? '|' : null,
                                (params.row.status === '0') ?
                                h('span', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        color: '#fc6c49',
                                        marginLeft: "6px"
                                    },
                                    on: {
                                        click: () => {
                                            this.handleRemove(params)
                                        }
                                    }
                                }, '删除') : null
                        ]);
                    }
                }
            ],
            data1: [],
            selections: [],
            showMedicalModal: false,
            modalType: '', // add新增 edit编辑 review查看
            formData: {},
            loading: false,
            showDelModal: false,
            curRecord: {},
            delLoading: false,
            saveLoading: false,
            yplb:[],
            disabledSave: false
        };
    },
    created() {
        let breadList = [
            { path: "/index", title: "首页" },
            {
                path: "",
                title: "药品目录管理"
            },
            {
                path: "/index/operation/drugmanagement/commondrug/list",
                title: "平台药品云目录"
            }
        ];
        this.$emit("changeBreadList", breadList);
    },
    computed: {
    },
    mounted() {
        this.findOperateDrugPage();
        this.findDrugDict();
    },
    methods: {
        loadPage(index) {
            this.filterObj.pageNo = index;
            this.findOperateDrugPage();
        },
        handleSearch() {
            this.filterObj.pageNo = 1;
            this.findOperateDrugPage(this.filterObj);
        },
        handleReset() {
            this.filterObj = this.deepClone(filterObj);
            this.findOperateDrugPage();
        },
        selectChange(selections) {
            this.selections = selections;
        },
        handleAddMedical() {
            this.modalType = 'add';
            this.formData = this.deepClone(formData);
            // statusItem.selections = [{value: '0', label: '未启用'}, {value: '1', label: '在用'}];
            this.showMedicalModal = true;
            console.log(this.formData)
        },
        handleRemove(record) {
            this.removeType = 'single';
            this.showDelModal = true;
            this.curRecord = record.row;
        },
        handleBatchDelete() {
            if (!this.selections.length) {
                this.$Message.error('请选择删除项');
            } else {
                this.removeType = 'batch';
                this.showDelModal = true;
            }
        },
        handleDel() {
            if (this.removeType === 'single') {
                this.delDrug();
            } else if (this.removeType === 'batch') {
                this.delBatchDrug();
            }
        },
        handleBatch() {
            this.functionJS.queryNavgationTo(this, "/index/directory/cloudCatalog/uploadPages/stepOne", {
            });
        },
        handleEdit(record) {
            this.modalType = 'edit';
            this.findKbaoOperateDrugEntity(record.row.id);
        },
        handleReview(record) {
            this.modalType = 'review';
            this.findKbaoOperateDrugEntity(record.row.id);
            console.log(this.formData)
        },
        handleSave() {
            this.disabledSave = true
            console.log(this.formData)
            this.$refs['formInline'].validate((valid) => {
                if (valid) {
                    console.log(this.formData);
                    if (this.modalType === 'add') {
                        this.insertKbaoOperateDrugEntity();
                        this.disabledSave = false
                    } else if (this.modalType === 'edit') {
                        this.updateKbaoOperateDrugEntity();
                        this.disabledSave = false
                    }
                } else {
                    this.$Message.error("请完整填写必填项!");
                    setTimeout(() => {
                        this.disabledSave = false
                    }, 5000);
                }
            })
        },
        findOperateDrugPage(params = {}) {
            const reqData = this.deepClone(this.filterObj);
            console.log(reqData)
            this.loading = true;
            this.$axios.post(api.findDhtboDrugPageList, reqData).then(res => {
                this.loading = false;
                if (res.data.code === 1) {
                    let ret = res.data.object.records;
                    this.count = res.data.object.total;
                    this.data1 = ret;
                    if (!ret || !ret.length) {
                        this.$Message.info('未查询到符合条件的记录')
                    }
                } else {
                    this.$Message.error('请求异常');
                    return false;
                }
            }).catch(() => {
                this.loading = false;
            });
        },
        findKbaoOperateDrugEntity(data) {
            this.$axios.post(api.findDhtboDrugById, {id:data}).then(res => {
                if (res.data.code === 1) {
                    this.showMedicalModal = true;
                    this.formData = this.deepClone(res.data.object);
                    if (!ret || !ret.length) {
                        this.$Message.info('未查询到符合条件的记录')
                    }
                } else {
                    this.$Message.error('请求异常');
                    return false;
                }
            }).catch(() => {
            });
        },
        findDrugDict() {
            this.$axios.post(api.findDrugDict,{}).then((res) => {
                if (!res.data.code) {
                    this.$Message.error('请求异常');
                    return false;
                }
                const obj = res.data.object;
                // 药品类别
                this.yplb = obj.ybflList
                this.drugCalss = obj.drugClassList
                this.ypjx = obj.jxlList
                this.zxdw = obj.jbdwList
                this.zxbzdw = obj.bzdwList
                this.ypyf = obj.gyljList
                this.yypc = obj.yypcList
                this.attr2 = obj.jldwList
            }).catch((res) => {
                console.log(res)
            })
        },
        insertKbaoOperateDrugEntity() {
            this.saveLoading = true;
            // console.log(JSON.stringify(this.formData));
            console.log('入参',this.formData);
            this.$axios.post(api.insertDhtboDrug, this.formData).then((res) => {
                console.log(res)
                this.saveLoading = false;
                if (res.data.code === 1) {
                    this.$Message.success('添加成功');
                    setTimeout(() => {
                        this.disabledSave = false
                    }, 1000);
                    this.showMedicalModal = false;
                    this.findOperateDrugPage();
                } else {
                    this.$Message.error(res.data.message);
                    this.disabledSave = false
                }
            }).catch((res) => {
                this.saveLoading = false;
                this.disabledSave = false
                console.log(res)
            })
        },
        updateKbaoOperateDrugEntity() {
            console.log('入参',this.formData)
            this.saveLoading = true;
            this.$axios.post(api.updateDhtboDrug, this.formData).then((res) => {
                this.saveLoading = false;
                if (res.data.code === 1) {
                    this.$Message.success('更新成功');
                    setTimeout(() => {
                        this.disabledSave = false
                    }, 1000);
                    this.showMedicalModal = false;
                    this.findOperateDrugPage();
                } else {
                    this.$Message.error(res.data.message);
                    this.disabledSave = false
                }
            }).catch((res) => {
                this.saveLoading = false;
                this.disabledSave = false
                console.log(res)
            })
        },
        delDrug() {
            let reqData = this.curRecord;
            this.delLoading = true;
            this.$axios.post(api.delDhtboDrug, reqData).then((res) => {
                this.delLoading = false;
                if (!res.data.code) {
                    this.$Modal.error({
                        content: res.data.object.map(item => `<p>${item}</p>`).join('<br />'),
                        okText: '确认',
                        onOk: () => {
                            this.showDelModal = false;
                        }
                    });
                    return false;
                }
                this.$Message.success('删除成功');
                this.findOperateDrugPage();
                this.showDelModal = false;
            }).catch((res) => {
                console.log(res)
                this.delLoading = false;
            })
        },
        delBatchDrug() {
            let reqData = {ids: this.selections.map((item) => item.id).join(',')};
            console.log(reqData)
            this.delLoading = true;
            this.$axios.post(api.delBatchDrug, reqData).then((res) => {
                console.log(res)
                this.delLoading = false;
                if (res.data.code === 1) {
                    this.$Message.success('删除成功');
                    this.findOperateDrugPage();
                    this.showDelModal = false;
                } else {
                    this.$Message.error(res.data.object.join('\n'));
                    return false;
                }
            }).catch((res) => {
                console.log(res)
                this.delLoading = false;
            })
        },
        deepClone(obj) {
            return JSON.parse(JSON.stringify(obj))
        }
    },
    watch: {
        'filterObj.pageSize'(nv, ov) {
            this.filterObj.pageNo = 1;
            this.findOperateDrugPage();
        },
    }
};
</script>
<style lang="less" scoped>
.list {
    width: 100%;
    min-width: 1200px;
    padding: 10px;
    margin: 0 auto;
    background: #fff;
    .margin-up-down {
        display: inline-block;
        margin: 10px 0;
    }
    .page {
        text-align: center;
        margin: 20px 0;
    }
}
.left-part {
    width: 100%;
    margin-bottom: 20px;
    border: 1px solid #f0f0f0;
    box-shadow: 0 4px 3px #ebedf8;
    border-radius: 5px;
    .title {
        font-size: 20px;
        padding-left: 15px;
        margin-bottom: 20px;
        color: #333;
        height: 40px;
        line-height: 40px;
        background: #ebedf8;         
    }
    .content{
        padding: 0 30px;
        .hongdian{
            margin-left:-11px;
        }
        // .contentitem{
        //     margin-bottom:20px;
        // }
        .tishi{
            color: #ff9966;
        }
    }
}
.drugmanagement-commondrug-list-MedicalModal {
    /deep/ .ivu-modal-wrap {
        label.ivu-form-item-label {
            padding-right: 0;
            height: 32px;
        }
        .ivu-modal-footer {
            display: none;
        }
        .btn-group {
            text-align: center;
            .save {
                width: 100px;
                margin-right: 20px;
            }
            .close {
                margin-left: 20px;
                width: 100px;
            }
        }
    }
    
}
.drugmanagement-commondrug-list-delModal {
    /deep/ .ivu-modal-wrap {
        .btn {
            width: 80px;
        }
    }
}
/deep/ .ivu-modal-wrap {
    .ivu-modal{
        float:right !important;
        background-color: #fff;
        border-radius: 10px;
        top: 0px;
        height: 100%;
    }
}
</style>
